/**
 * 生成gruntfile配置
 * 1.选出>=300k的图片 手动写到配置内 （待确定是否会导致配置文件过大
 * 2.选出>=300k的图片 复制到另一目录内 配置内使用该目录 执行完压缩后覆盖回去（
 */
let fs = require('fs');
let path = require("path");
let exec = require('child_process').exec;
let readline = require('readline');

let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let limitSize = 300;

let tempDir = `tmp`;
let largeFiles = [];
let backFileAmount = 0;
let srcDir;
let options = process.argv;
let baseName;
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir);
} else {
    //清空
    emptyDir(tempDir);
    fs.mkdirSync(tempDir);
}
// /Users/xyxy/Documents/WORKS/legendClient/legendClient/assets/resources
if (options[2]) {
    srcDir = options[2];
    baseName = path.basename(srcDir);;
    //开始
    startMin();
} else {
    rl.question('输入resources路径（或直接拖入resource/目录到控制台）', (src) => {
        // TODO: Log the answer in a database
        srcDir = src.trim();
        baseName = path.basename(srcDir);;
        console.log('baseName ',baseName);
        
        startMin();
        rl.close();
    });
}

function startMin() {
    readDir(srcDir);
    console.log('largeFiles', largeFiles, '数量', largeFiles.length);
    //复制文件
    largeFiles.forEach(file => {
        // let filePath = path.dirname(file.src).split('resources/');
        let filePath = path.dirname(file.src).split(`${baseName}/`);
        let destPath = tempDir + '/' + (filePath[1]||'');
        console.log(' path.dirname(file.src)', path.dirname(file.src))
        console.log('destPath',destPath);
        if (!fs.existsSync(destPath)) {
            mkdirsSync(destPath);
        }
        fs.copyFileSync(file.src, destPath + '/' + file.name);
        console.log('复制完成', file.src + ' ===> ' + destPath + '/' + file.name);
    });
    console.log("复制完成 开始压缩 请等待")

    //使用命令行
    let cmd = 'grunt imagemin'
    exec(cmd, function (err, stdout, stderr) {
        console.log(err, stdout, stderr);
        if (!err) {
            console.log('压缩完成 , 结果 ', stdout);
            //压缩完成 覆盖回项目
            writeBack(tempDir);
            console.log(`大文件数：${largeFiles.length} 写回 ${backFileAmount}`);
            if (largeFiles.length == backFileAmount) {
                console.log('覆盖完成 , 结果 ', stdout);
            } else {
                console.log('覆盖完成 文件数不匹配');
            }
        } else {
            console.log('压缩出错 ', err);
        }
    });
}




//整理大文件
function readDir(src) {
    let dir = fs.readdirSync(src);
    console.log(src, dir);
    dir.forEach(d => {
        let stat = fs.statSync(src + '/' + d);
        if (stat.isDirectory()) {
            console.log(d, 'isDirectory ');
            readDir(src + '/' + d);
        } else if(path.extname(src+'/'+d)=='.png'||path.extname(src+'/'+d)=='.jpg'){
            console.log(d, 'size:', stat.size);
            if (stat.size >= limitSize * 1000) {
                console.log(d, '大于300K');
                largeFiles.push({
                    src: src + '/' + d,
                    size: stat.size,
                    name: d
                });
            }
        }else{
            console.log('跳过非图片文件');
        }
    });
}

//覆盖回项目
function writeBack(src) {
    let dir = fs.readdirSync(src);
    console.log(src, dir);
    dir.forEach(d => {
        let stat = fs.statSync(src + '/' + d);
        if (stat.isDirectory()) {
            writeBack(src + '/' + d);
        } else {
            //写回 
            let fullPath = src + '/' + d;
            //切割出相对路径
            console.log('fullpath', fullPath);
            let p = fullPath.split(`${tempDir}/`)[1];
            fs.copyFileSync(fullPath, srcDir + '/' + p);
            backFileAmount++;
        }
    });
}

//递归创建目录 同步方法  
function mkdirsSync(dirname) {
    //console.log(dirname);  
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

function emptyDir(dir) {
    var files = [];
    if (fs.existsSync(dir)) {
        files = fs.readdirSync(dir);
        files.forEach(function (file, index) {
            var curPath = dir + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                emptyDir(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(dir);
    }
}
function isFile(path) {
    return exists(path) && fs.statSync(path).isFile();
}
function isDir(path) {
    return exists(path) && fs.statSync(path).isDirectory();
}  